using System;
using System.Web;
using System.Xml;
using System.Web.UI;
using umlungu.engineX.blogX;
using log4net;

/*	-----------------------------------------------------------------------	
	Copyright:	umlungu consulting (pty) ltd
	Author:		Alan Benington
	Started:	2008-06-14
	Status:		release	
	Version:	2.0.0
	Build:		20080614
	License:	GNU General Public License
	-----------------------------------------------------------------------	*/

/*	-----------------------------------------------------------------------	
	Development Notes:
	==================
	20080614:	Initial release.
	---------------------------------------------------------------------------	*/

namespace umlungu.engineX.blogX.WebsiteX {
    /// <summary>
    /// Description of the WebsiteXShop class.
    /// <para>Additional information about the class</para>
    /// </summary>
    public class WebsiteXShop : x_broker {
        #region Invisible properties
        private bool testing = false;
        private const string logsep = ",";
        private const string logsDir = "Data/Logs/Data/";
        //private NameSpace.WebService webservice;
        #endregion

        #region properties from provisioner
        private x_config config;
        private const string CONFIG_ROOT = "Example";
        private const string CONFIG_ID = "webservice";
        #endregion

        #region Constant name strings
        private const string logid = "WebsiteXShop";
        #endregion

        #region Constant error strings
        private const string error_no_error = "Not an error";
        private const string error_webshop = "WebsiteXShop error::";
        private const string error_webshop_test = " test error";
        private const string error_webshop_login = " Error logging in to account: ";
        private const string error_webshop_boost = " Error boosting account: ";
        private const string error_webshop_email = " Error updating email notification: ";
        private const string error_webshop_pay = " Error making cactus payment: ";
        #endregion

        #region Visible properties
        public static readonly ILog Logger = LogManager.GetLogger(typeof(WebsiteXShop));
        #endregion

        #region Constructors/Destructors
        /// <overloads>Constructor</overloads>
        /// <summary>Default constructor</summary>
        /// <param name="thispage">The web application Page object</param>
        public WebsiteXShop(displayX thispage) : base(thispage) {
            log4net.Config.XmlConfigurator.Configure();
            config = new x_config();
            //webservice = new NameSpace.WebService();
            //webservice.Url = getUrl();
        }
        #endregion

        #region Public methods
        public override void Process(string type) {
            Logger.Info(String.Concat(logid, "_Process:", type));
            switch (type) {
                case "test": test(); break;
                case "addItem": addItem(); break;
                case "remItem": remItem(); break;
                case "editItemPlus": editItem(1); break;
                case "editItemMinus": editItem(-1); break;
                case "checkShopCartEmpty": checkShopCartEmpty(); break;
            }
        }
        public void ProcessContent(XmlElement contel) {
            if (testing)
                test(contel);
            else
                nottest(contel);
        }
        #endregion

        #region Protected methods
        #endregion

        #region Private methods
        
        private void checkShopCartEmpty() { 
            try{

                XmlNode shopcart = UIPage.UserProfile.Node("shopcart");
                ///Logger.Debug(String.Concat("Shopcart: ", shopcart.InnerXml.ToString()));
                if (shopcart.InnerXml.ToString() == "") {
                    throw (new displayException("products_shop_empty"));
                }

            } catch (displayException e) {
                throw (e);
            }
        }
        
        
        //addItem Method - used to add item to the shopping cart
        private void addItem() { 
            //get items form the UIPage
            string itemPrice = UIPage.UserProfile.Value("addItemPrice");
            string itemName  = UIPage.UserProfile.Value("addItemName");
            string itemId = UIPage.UserProfile.Value("addItemId");
            string itemQuantity = UIPage.UserProfile.Value("addItemQuantity");

            

            if (itemPrice == "" || itemName == "" || itemId == "" || itemQuantity == "") return;
            double itemSubtotal = int.Parse(itemQuantity) * double.Parse(itemPrice);


            //check to see if the item exists, if it does only update the quantity and subtotal, else add a new item
            XmlNode testNode = UIPage.UserProfile.Node("shopcart").SelectSingleNode(String.Concat("item[@id='", itemId, "']"));
            //Logger.Debug(testNode.InnerText.ToString());
            if(testNode != null){
                int getItemQuantity = int.Parse(UIPage.UserProfile.Node("shopcart").SelectSingleNode(String.Concat("item[@id='", itemId, "']/quantity")).InnerText.ToString());
                double getItemPrice = double.Parse(UIPage.UserProfile.Node("shopcart").SelectSingleNode(String.Concat("item[@id='", itemId, "']/price")).InnerText.ToString());

                itemQuantity = (int.Parse(itemQuantity) + getItemQuantity).ToString();
                itemSubtotal = int.Parse(itemQuantity) * getItemPrice;

                UIPage.UserProfile.Node("shopcart").SelectSingleNode(String.Concat("item[@id='", itemId, "']/quantity")).InnerText = itemQuantity.ToString();
                UIPage.UserProfile.Node("shopcart").SelectSingleNode(String.Concat("item[@id='", itemId, "']/subtotal")).InnerText = itemSubtotal.ToString();
            }else{            
                 //add a new node to the userProfile xml
                XmlDocument item = new XmlDocument();

                string itemXML = "<item id=\"{0}\"><name>{1}</name><price>{2}</price><quantity>{3}</quantity><subtotal>{4}</subtotal></item>";

                itemXML = String.Format(itemXML, itemId, itemName, itemPrice, itemQuantity, itemSubtotal);
                item.LoadXml(itemXML);
                UIPage.UserProfile.AddNode("shopCartItem");
                UIPage.UserProfile.Node("shopCartItem").InnerXml = item.InnerXml;
                XmlNode shopcart = UIPage.UserProfile.Node("shopcart");
                shopcart = UIPage.UserProfile.Node("shopcart").AppendChild(UIPage.UserProfile.Node("shopCartItem/item"));
            }

            UIPage.UserProfile.Clear("addItemPrice");
            UIPage.UserProfile.Clear("addItemName");
            UIPage.UserProfile.Clear("addItemId");
            UIPage.UserProfile.Clear("addItemQuantity");

        }

        //remItem Method - used to remove item(s) from the shopping cart
        private void remItem() {
                //get the ID of the item to delete
            try{    
                string itemId = _GetRequest(false, "delId", "");
                XmlNode delNode = UIPage.UserProfile.Node("shopcart").SelectSingleNode(String.Concat("item[@id = '", itemId, "']"));
                UIPage.UserProfile.Node("shopcart").RemoveChild(delNode);

                checkShopCartEmpty();
            } catch (x_exception e) {
                throw (new x_exception("products_shop_empty", String.Concat(error_webshop, error_webshop_email, e.Code, " - ", e.Message)));
            } catch (Exception e) {
                throw (new x_exception("products_shop_empty", String.Concat(error_webshop, error_webshop_email, e.Message)));
            }
        }

        private void editItem(int addNum) {
            string itemId = _GetRequest(false, "editId", "");
            XmlNode editNode = UIPage.UserProfile.Node("shopcart").SelectSingleNode(String.Concat("item[@id = '", itemId, "']/quantity"));
            int total = int.Parse(editNode.InnerText.ToString()) + addNum;
            if (total <= 0) total = 1;
            editNode.InnerText = total.ToString() ;

            editNode = UIPage.UserProfile.Node("shopcart").SelectSingleNode(String.Concat("item[@id = '", itemId, "']/price"));

            double itemPrice = double.Parse(editNode.InnerText.ToString());

            double itemSubtotal = double.Parse(total.ToString()) * itemPrice;
            editNode = UIPage.UserProfile.Node("shopcart").SelectSingleNode(String.Concat("item[@id = '", itemId, "']/subtotal"));
            editNode.InnerText = itemSubtotal.ToString();

        }

        #endregion

        #region Private utility methods
        private string getUrl() {
            return config.Value(String.Concat(CONFIG_ROOT, "/Url[@id='", CONFIG_ID, "']"));
        }
        private void test() {
        }
        private void test(XmlElement contel) {
            XmlDocument doc = contel.OwnerDocument;
            XmlNode page = contel.SelectSingleNode("//content/page");
        }
        private void nottest() {
        }
        private void nottest(XmlElement contel) {
            XmlDocument doc = contel.OwnerDocument;
            XmlNode page = contel.SelectSingleNode("//content/page");
        }
        #endregion
    }
}
